import time
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
from auto.sleep.push import auto_ai_sleep
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from auto.sleep.push import auto_ai_sleep
app = Flask(__name__)
CORS(app)  # 启用CORS支持

# 添加首页路由
@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@app.route('/send', methods=['POST'])
def receive_message():
    data = request.get_json()
    message = data.get('message', '')
    start = time.time()
    auto_ai_sleep.future_for_sleep(message)
    elapsed_time = time.time() - start
    return jsonify({'message': f'收到消息: {message} {elapsed_time:.4f} 秒'})

if __name__ == '__main__':
   
    job_defaults = {
        'coalesce': False,
        'max_instances': 1
    }
    auto_ai_sleep.future_for_sleep(None)
    # 调度器组件
    # 区别主要在于BlockingScheduler会阻塞主线程的运行，而BackgroundScheduler不会阻塞
    backsched = BackgroundScheduler(job_defaults=job_defaults, timezone='Asia/Shanghai')
    # future_for_sleep callable函数 习惯养成--早睡早起
    # crontab 是 Linux 系统中用于设置周期性被执行的指令的命令
    # 0 0 * * *	每天的午夜（0 点）执行一次
    backsched.add_job(auto_ai_sleep.future_for_sleep, CronTrigger.from_crontab("0 21 * * *"),args=[None], id="get_up")
    backsched.start()
   
 
    # 启动Flask应用 blocked 阻塞
    app.run(host='0.0.0.0', port=5000, debug=True)  # 添加 host='0.0.0.0' 允许外部访问
